//
//  LianliankanViewController.m
//  oc_demo
//
//  Created by haigui on 2021/11/8.
//

#import "LianliankanViewController.h"

@interface LianliankanViewController ()
{
    int _line;
    int _column;
    int _total;
    int _group;//要有多少组数据
}

@property (nonatomic, assign) BOOL alreadySelected;

@property (nonatomic, strong) UIButton *startButton;

@property (nonatomic, strong) UIView *layerView,*bgView;

@property (nonatomic, strong) NSMutableArray *arrBtn,*arrPoint;

@property (nonatomic, strong) NSMutableArray *arrItem;
@end

@implementation LianliankanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *shareBarButton = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"share_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shareBarButtonClick:)];
    self.navigationItem.rightBarButtonItem = shareBarButton;
    
    _line = 8;
    _column = 8;
    _total = _line * _column;
    _group = 20;//要有多少组数据
    _arrBtn = [NSMutableArray array];
    _arrPoint = [NSMutableArray array];
    
    NSMutableArray *arrGroupData = [NSMutableArray array];
    for (int i = 0; i<_group; i++) {
        int t = arc4random() % _total;
        [arrGroupData addObject:@(t)];
        [arrGroupData addObject:@(t)];
    }
    
    //将group组数据裂变到total条
    _arrItem = [NSMutableArray array];
    for (int i = 0; i<_total; i++) {
        if (_arrItem.count + arrGroupData.count < _total) {
            [_arrItem addObjectsFromArray:arrGroupData];
        }else{
            for (int j = 0; j<arrGroupData.count; j++) {
                if (_arrItem.count < _total) {
                    [_arrItem addObject:arrGroupData[j]];
                    continue;
                }
                break;
            }
        }
        if (_arrItem.count == _total) {
            break;
        }
    }
    //打乱数组数据的顺序
    _arrItem = (NSMutableArray *)[_arrItem sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        int seed = arc4random_uniform(2);
        if (seed) {
            return [obj1 compare:obj2];
        } else {
            return [obj2 compare:obj1];
        }
    }];

    _layerView = [[UIView alloc]init];
    _layerView.center = CGPointMake(SCREEN_WIDTH*0.5, (SCREEN_HEIGHT-NavigationBarHeight)*0.5);
    _layerView.bounds = CGRectMake(0, 0, SCREEN_WIDTH-20, SCREEN_WIDTH-20);
    _layerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_layerView];

    UIView *bgView = [[UIView alloc]init];
    bgView.center = CGPointMake(SCREEN_WIDTH*0.5, (SCREEN_HEIGHT-NavigationBarHeight)*0.5);
    bgView.bounds = CGRectMake(0, 0, SCREEN_WIDTH-20, SCREEN_WIDTH-20);
//    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];

    _bgView = bgView;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    CGFloat W = (_bgView.width-40)/_column;
    CGFloat H = (_bgView.height-40)/_line;
    for (int i = 0; i<_arrItem.count; i++) {
        NSNumber *number = _arrItem[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(20+W*(i%_line), 20+H*(i/_column), W, H);
        button.backgroundColor = [UIColor whiteColor];
        button.titleLabel.font = [GlobalFile fontOfSize14];
        [button setTitleColor:[GlobalFile textColorWithDefaultBlack] forState:UIControlStateNormal];
        [button setTitle:number.stringValue forState:UIControlStateNormal];
        button.layer.cornerRadius = 3;
        button.clipsToBounds = YES;
        button.layer.borderColor = [GlobalFile textColorWithDefaultBlack].CGColor;
        button.layer.borderWidth = 1;
        button.tag = i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bgView addSubview:button];

        [_arrBtn addObject:button];
        [_arrPoint addObject:[NSValue valueWithCGPoint:button.center]];
    }
}
- (void)buttonClick:(UIButton *)btn{
    if (!_alreadySelected) {
        btn.layer.borderColor = [GlobalFile themeColor].CGColor;
        _startButton = btn;
        _alreadySelected = YES;
    }else{
        if (btn == _startButton) {
            return;
        }
        /**
         startButton:起点
         btn        :终点
         */
        if ([_startButton.titleLabel.text isEqualToString:btn.titleLabel.text]) {
            NSMutableArray *arrDrawPoint = [NSMutableArray array];
            UIBezierPath *bezierPath = [UIBezierPath bezierPath];
            [bezierPath moveToPoint:_startButton.center];
            CAShapeLayer *layer;
            if (_startButton.centerY > btn.centerY) {//终点在起点 上方
                if (_startButton.centerX > btn.centerX) {//终点在起点的 左上方
                    
                }else if (_startButton.centerX < btn.centerX){//终点在起点的 右上方
                    
                }else{//终点在起点的 正上方
                    
                }
            }else if (_startButton.centerY < btn.centerY){//终点在起点 下方
                if (_startButton.centerX > btn.centerX) {//终点在起点的 左下方
                    
                }else if (_startButton.centerX < btn.centerX){//终点在起点的 右下方
                    
                }else{//终点在起点的 正下方
                    
                }
            }else{
                //一条直线上 横向
                if (_startButton.centerX > btn.centerX) {//终点在起点的 左侧
                    BOOL canDraw = YES;
                    for (NSInteger i = btn.tag - 1; i>=_startButton.tag; i--) {
                        UIButton *indexBtn = _arrBtn[i];
                        if ([_arrPoint containsObject:[NSValue valueWithCGPoint:indexBtn.center]]) {
                            canDraw = NO;
                            [arrDrawPoint removeAllObjects];
                            break;
                        }else{
                            [arrDrawPoint addObject:[NSValue valueWithCGPoint:indexBtn.center]];
                        }
                    }
                    if (canDraw) {
                        for (NSValue *value in arrDrawPoint) {
                            CGPoint point = value.CGPointValue;
                            [bezierPath addLineToPoint:point];
                        }
                        [arrDrawPoint removeAllObjects];
                    }
                }else if (_startButton.centerX < btn.centerX){//终点在起点的 右侧
                    BOOL canDraw = YES;
                    for (NSInteger i = _startButton.tag + 1; i<=btn.tag; i++) {
                        UIButton *indexBtn = _arrBtn[i];
                        if ([_arrPoint containsObject:[NSValue valueWithCGPoint:indexBtn.center]] && indexBtn.tag != btn.tag) {
                            canDraw = NO;
                            [arrDrawPoint removeAllObjects];
                            break;
                        }else{
                            [arrDrawPoint addObject:[NSValue valueWithCGPoint:indexBtn.center]];
                        }
                    }
                    if (canDraw) {
                        for (NSValue *value in arrDrawPoint) {
                            CGPoint point = value.CGPointValue;
                            [bezierPath addLineToPoint:point];
                        }
                        [arrDrawPoint removeAllObjects];
                    }
                }else{
                    
                }
                layer = [self addLineByBezierPath:bezierPath];
                [_layerView .layer addSublayer:layer];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [layer removeFromSuperlayer];
                [UIView animateWithDuration:0.2 animations:^{
                    _startButton.transform = CGAffineTransformMakeScale(0.01, 0.01);
                    btn.transform = CGAffineTransformMakeScale(0.01, 0.01);
                } completion:^(BOOL finished) {
                    [_arrPoint removeObject:[NSValue valueWithCGPoint:_startButton.center]];
                    [_arrPoint removeObject:[NSValue valueWithCGPoint:btn.center]];
                    [_startButton removeFromSuperview];
                    _startButton = nil;
                    [btn removeFromSuperview];
                }];
            });
        }else{
            _startButton.layer.borderColor = [GlobalFile textColorWithDefaultBlack].CGColor;
            btn.layer.borderColor = [GlobalFile themeColor].CGColor;
            _startButton = btn;
        }
    }
}
- (CAShapeLayer *)addLineByBezierPath:(UIBezierPath *)bezierPath{
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    basicAnimation.duration = 0.1;
    basicAnimation.repeatCount = 1;
    basicAnimation.removedOnCompletion = YES;
    basicAnimation.fromValue = @(0);
    basicAnimation.toValue = @(1);

    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.lineWidth = 2;
    layer.strokeColor = [GlobalFile themeColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.path = bezierPath.CGPath;
    [layer addAnimation:basicAnimation forKey:@"strokeEnd"];
    return layer;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
